package ipt.br.arbio.generic.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;


@SuppressWarnings("unchecked")
public abstract class GenericImpl<T> {

	protected Session session;
	private Class<T> clazz;
	
	public GenericImpl(Session session) {
		this.clazz = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
		this.session = session;
	}
	
	public GenericImpl() {
		this(null);
	}
	
	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	public T save(final T o) {
		return (T) session.save(o);
	}

	public void delete(final T o) {
		session.delete(o);
	}

	public T get(final Integer id) {
		return (T) session.get(clazz, id);
	}

	public void saveOrUpdate(final T o) {
		session.saveOrUpdate(o);
	}
	
	public T load(final Integer id){
		return (T) session.load(clazz, id);
	}

	public List<T> listAll() {
		final Criteria crit = session.createCriteria(clazz);
		return crit.list();
	}
}
